package chaw.android.train.MoreActivities;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.train.AllBoardActivity;
import chaw.android.train.BoardViewActivity;
import chaw.android.train.FavoriteActivity;
import chaw.android.train.MoreActivity;
import chaw.android.train.R;
import chaw.android.train.TrainTravelActivity;
import chaw.android.util.BoardItem;
import chaw.android.util.HttpRequestManager;
import chaw.android.util.LoadBitMap;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;
import chaw.android.util.TimeCheck;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MoreStoryActivity extends ListActivity {
	private ImageView btnBack, btnEdit;
	private ArrayList<JSONObject> json_list;
	private BoardAdapter nadapter;
	private WebView bannerWebView;
	private WebViewClient webViewClient;
	private ArrayList<BoardItem> boardList;
	private String json_modify;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.more_story);
	    
	    json_modify = "";
	    
	    bannerWebView = (WebView) findViewById(R.id.banner);
	    webViewClient = new WebViewClient();
//		bannerWebView.setWebViewClient(webViewClient);
//		bannerWebView.loadUrl(ServerURL.bannerWebView);
	    bannerWebView.setWebViewClient(new WebViewClient(){
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url){
				String[] values = url.split("!");
				if(values[1].equals("app")){
					if(values[2].equals("live")){
						Intent intent = new Intent(getBaseContext(), AllBoardActivity.class);
						startActivity(intent);
						
					}
					else if(values[2].equals("enjoy")){
						Intent intent = new Intent(getBaseContext(), MoreSpecialActivity.class);
						startActivity(intent);
					}
				}
				else if(values[1].equals("board")){
					StationIdAsynkTask task = new StationIdAsynkTask();
					String[] params = new String[]{ ServerURL.stationIdFromBoard, "board_id", values[2]};
					task.execute(params);
				}
				else if(values[1].equals("web")){
					Intent intent = new Intent(Intent.ACTION_VIEW); 
					Uri uri = Uri.parse(values[2]); 
					intent.setData(uri); 
					startActivity(intent);
				}
				return true;
			}
		});
		bannerWebView.loadUrl(ServerURL.bannerWebView(Preferences.getValue(getBaseContext(), "device_token"),
													  Preferences.getValue(getBaseContext(), "user_id"),
													  Preferences.getValue(getBaseContext(), "version")));
		bannerWebView.getSettings().setJavaScriptEnabled(true);
		
	    btnBack = (ImageView) findViewById(R.id.btnBack);
	    btnEdit = (ImageView) findViewById(R.id.btnEdit);
	    
	    btnBack.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				MoreActivity parentActivity = (MoreActivity) getParent();
				parentActivity.finishFromChild(MoreStoryActivity.this);
			}
		});
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setListView();
		for(int i = 0 ; i < 5; i++)
        	TrainTravelActivity.tabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.bg_nav1);
	}
	
	private void setListView(){
		json_list = new ArrayList<JSONObject>();
		
		DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[] { ServerURL.downLoadStoriesWithUser, "user_id", Preferences.getValue(getBaseContext(), "user_id") };
		task.execute(params);
	}

    private final static Comparator<JSONObject> myComparator= new Comparator<JSONObject>() {
        private final Collator collator = Collator.getInstance();
		@Override
		public int compare(JSONObject object1, JSONObject object2) {
        	try {
				return collator.compare(object1.get("date"), object2.get("date"));
			} catch (JSONException e) {
				e.printStackTrace();
				return 0;
			}
		}
    };

	@Override
	public void onListItemClick(ListView parent, View v, int position, long id){
		BoardItem clickedItem = (BoardItem) parent.getItemAtPosition(position);
		Intent boardViewIntent = new Intent(getBaseContext(), TrainTravelActivity.class);
		boardViewIntent.putExtra("board_id", clickedItem.getId());
		boardViewIntent.putExtra("station_id", clickedItem.getStationId());
		boardViewIntent.putExtra("station_name", clickedItem.getStation());
		boardViewIntent.setAction("BoardViewActivity");
		startActivity(boardViewIntent);
	}
	
	private class BoardAdapter extends ArrayAdapter<BoardItem>{
		private ArrayList<BoardItem> items;
		private int rsrc;
		
		public BoardAdapter(Context ctx, int rsrcId, ArrayList<BoardItem> data){
			super(ctx, rsrcId, data);
			this.items = data;
			this.rsrc = rsrcId;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(rsrc, null);
			}
			BoardItem e = items.get(position);
			if(e != null){
				String title = e.getTitle();
				if(title.length() > 14){
					title = title.substring(0, 13) + "..";
				}
				((TextView)v.findViewById(R.id.board_title)).setText(title);
				((TextView)v.findViewById(R.id.time)).setText(TimeCheck.checkTime(e.getDate()));
//				if(!e.getReplyCount().equalsIgnoreCase("0")){
//					((TextView)v.findViewById(R.id.reply_count)).setText(e.getReplyCount());
//					((TextView)v.findViewById(R.id.reply_count)).setBackgroundResource(R.drawable.bg_count);
//				}
				((TextView)v.findViewById(R.id.stationName)).setText(e.getStationName());

				ImageView image = ((ImageView)v.findViewById(R.id.user_pic));
				if(e.getImage() == null ){
					image.setImageResource(R.drawable.icon_nophoto_b);
				}
				else{
					image.setImageBitmap(e.getImage());
				}
				ImageView i = (ImageView)v.findViewById(R.id.theme1);
				if(e.getMeet().equals("1")){
					i.setImageResource(R.drawable.icon_theme_meet);
					i = nextIcon(v,i);
				}
				if(e.getRestaurant().equals("1")){
					i.setImageResource(R.drawable.icon_theme_food);
					i = nextIcon(v,i);
				}
				if(e.getPlace().equals("1")){
					i.setImageResource(R.drawable.icon_theme_tour);
					i = nextIcon(v,i);
				}
				if(e.getLodge().equals("1")){
					i.setImageResource(R.drawable.icon_theme_lodge);
					i = nextIcon(v,i);
				}
				if(e.getEtc().equals("1")){
					i.setImageResource(R.drawable.icon_theme_etc);
					i = nextIcon(v,i);
				}
				v = iconReset(v, i);
			}
			return v;
		}
	}

	public ImageView nextIcon(View v, ImageView i){
		if(i.equals(v.findViewById(R.id.theme1))){
			i = (ImageView)v.findViewById(R.id.theme2);
		}
		else if(i.equals(v.findViewById(R.id.theme2))){
			i = (ImageView)v.findViewById(R.id.theme3);
		}
		else if(i.equals(v.findViewById(R.id.theme3))){
			i = (ImageView)v.findViewById(R.id.theme4);
		}
		else if(i.equals(v.findViewById(R.id.theme4))){
			i = (ImageView)v.findViewById(R.id.theme5);
		}
		return i;
	}
	public View iconReset(View v, ImageView i){
		if(i.equals(v.findViewById(R.id.theme1))){
			((ImageView)v.findViewById(R.id.theme1)).setImageDrawable(null);
			i = (ImageView)v.findViewById(R.id.theme2);
		}
		if(i.equals(v.findViewById(R.id.theme2))){
			((ImageView)v.findViewById(R.id.theme2)).setImageDrawable(null);
			i = (ImageView)v.findViewById(R.id.theme3);
		}
		if(i.equals(v.findViewById(R.id.theme3))){
			((ImageView)v.findViewById(R.id.theme3)).setImageDrawable(null);
			i = (ImageView)v.findViewById(R.id.theme4);
		}
		if(i.equals(v.findViewById(R.id.theme4))){
			((ImageView)v.findViewById(R.id.theme4)).setImageDrawable(null);
			i = (ImageView)v.findViewById(R.id.theme5);
		}
		if(i.equals(v.findViewById(R.id.theme5))){
			((ImageView)v.findViewById(R.id.theme5)).setImageDrawable(null);
		}
		return v;
	}
	
	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(final String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			json_modify = result;
			DownloadAsynkTask2 task = new DownloadAsynkTask2();
			task.execute(new String[]{result});
		}
	}

	private class DownloadAsynkTask2 extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = urls[0];

			try {
				JSONObject json_data = new JSONObject(response);
				JSONArray json_arr = json_data.getJSONArray("boards");
				for(int i = 0 ; i < json_arr.length(); i++){
					JSONObject json_obj = (JSONObject) json_arr.get(i);
					json_list.add(json_obj);
				}
				Collections.sort(json_list, myComparator);
				
				boardList = new ArrayList<BoardItem>();
				boardList.clear();
				for(int i = 0 ; i < json_list.size() ; i++){
					JSONObject eachStory = (JSONObject)json_arr.get(i);
					JSONObject eachTheme = eachStory.getJSONObject("theme");
					Bitmap image_url = null;
					if(eachStory.get("image_main").equals("0")){
						image_url = null;
					}
					else if(eachStory.get("image_main").equals("1")){
						image_url = LoadBitMap.fromURL(eachStory.get("image_url_1").toString());
					}
					else if(eachStory.get("image_main").equals("2")){
						image_url = LoadBitMap.fromURL(eachStory.get("image_url_2").toString());
					}
					else if(eachStory.get("image_main").equals("3")){
						image_url = LoadBitMap.fromURL(eachStory.get("image_url_3").toString());
					}
					else if(eachStory.get("image_main").equals("4")){
						image_url = LoadBitMap.fromURL(eachStory.get("image_url_4").toString());
					}
					else{
						image_url = null;
					}
					BoardItem eachBoard = new BoardItem(eachStory.getString("board_id"), eachStory.getString("title"), eachTheme.getString("meet"), 
												eachTheme.getString("restaurant"), eachTheme.getString("place"), 
												eachTheme.getString("lodge"), eachTheme.getString("etc"), 
												image_url, eachStory.getString("date"), 
												eachStory.getString("station_name"), eachStory.getString("station_id"));
					boardList.add(eachBoard);
					boardList.get(boardList.size()-1).setStationName(eachStory.getString("station_name"));
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			nadapter = new BoardAdapter(getBaseContext(), R.layout.favorite_page_row, boardList);
		    ListView lv = getListView();
		    lv.setAdapter(nadapter);
		    
		    btnEdit.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					MoreActivity parentActiviy = (MoreActivity) getParent();
					Intent intent = new Intent(getBaseContext(), ModifyMyStoryActivity.class);
					intent.putExtra("modify_list", boardList);
					parentActiviy.startChildActivity("modifyMyStoryActivity", intent);
				}
			});
		}
	}
	private class StationIdAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				JSONObject station = new JSONObject(result);
				String station_id = station.get("station_id").toString();
				String station_name = station.get("station_name").toString();
				String board_id = station.get("board_id").toString();
				Intent intent = new Intent(getBaseContext(), BoardViewActivity.class);
				intent.putExtra("board_id", board_id);
				intent.putExtra("station_id", station_id);
				intent.putExtra("station_name", station_name);
				TrainTravelActivity tab = (TrainTravelActivity) getParent();
		        TrainTravelActivity.tabHost.setCurrentTab(3);
				tab.onTabChanged("Tab4");
				((FavoriteActivity) tab.getCurrentActivity()).startChildActivity("BoardView", intent);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
